package org.cloud.admin.auth.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.cloud.admin.auth.constant.AuthRedisConstants;
import org.cloud.admin.auth.holder.AppHolder;
import org.cloud.admin.auth.service.SysUserRoleService;
import org.cloud.admin.auth.vo.LoginedUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 应用拦截器
 * @author wangyuan
 * @since 2019年6月5日 下午5:33:05
 *
 */
@Component
public class AuthHandlerInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Resource(name = "valueOperations")
    private ValueOperations<String, LoginedUserVo> loginedValueOperations;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//根据token获取当前请求的用户信息并放到线程缓存中
		String accessToken = getTokenFromRequest(request);
		
		//从数据库中获取当前用户信息，后期改为从redis中获取
		LoginedUserVo loginedUser = loginedValueOperations.get(AuthRedisConstants.LOGINED_USER_KEY_PREFIX + accessToken);
		if(loginedUser == null) {
			response.sendError(HttpStatus.SC_BAD_REQUEST, "根据用户token未查询到用户登录信息");
			return false;
		}
		List<Long> roleIds = sysUserRoleService.queryRoleIdList(loginedUser.getId());
		loginedUser.setRoleIdList(roleIds);
		
		//放入线程缓存中
		AppHolder.setLoginedUser(loginedUser);
		
		return super.preHandle(request, response, handler);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		AppHolder.setLoginedUser(null);
		
		super.afterCompletion(request, response, handler, ex);
	}




	/**
	 * 从请求中获取token
	 * @param request
	 * @return
	 */
	private String getTokenFromRequest(HttpServletRequest request){
        //从header中获取token
        String token = request.getHeader("Auth-Token");

        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        return token;
    }
	
}
